// 用户数据管理模块
import { UserRole, PermissionChecker } from '@/jjk/Permissions'

export interface User {
  id: string
  username: string
  password: string // 在实际应用中应该加密存储
  name: string
  role: UserRole
  department?: string
  position?: string
  avatar?: string
  email?: string
  phone?: string
  isActive: boolean
  createdAt: string
  lastLoginAt?: string
}

// 预定义的5个用户账号
export const predefinedUsers: User[] = [
  {
    id: 'u001',
    username: 'jiangjiankai',
    password: 'jjk123456',
    name: '姜建凯',
    role: UserRole.SUPER_ADMIN,
    department: '信息科',
    position: '系统管理员',
    avatar: '/avatars/admin.jpg',
    email: 'jiangjiankai@hospital.com',
    phone: '13800000001',
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 'u002',
    username: 'guomengzhe',
    password: 'gmz123456',
    name: '郭梦哲',
    role: UserRole.DEAN,
    department: '院办',
    position: '院长',
    avatar: '/avatars/dean.jpg',
    email: 'guomengzhe@hospital.com',
    phone: '13800000002',
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 'u003',
    username: 'zhangyiwe',
    password: 'zyw123456',
    name: '张译文',
    role: UserRole.DIRECTOR,
    department: '内科',
    position: '内科主任',
    avatar: '/avatars/director.jpg',
    email: 'zhangyiwe@hospital.com',
    phone: '13800000003',
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 'u004',
    username: 'yaoyuan',
    password: 'yy123456',
    name: '姚远',
    role: UserRole.DOCTOR,
    department: '内科',
    position: '主治医师',
    avatar: '/avatars/doctor.jpg',
    email: 'yaoyuan@hospital.com',
    phone: '13800000004',
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 'u005',
    username: 'limengran',
    password: 'lmr123456',
    name: '李梦然',
    role: UserRole.NURSE,
    department: '内科',
    position: '主管护师',
    avatar: '/avatars/nurse.jpg',
    email: 'limengran@hospital.com',
    phone: '13800000005',
    isActive: true,
    createdAt: '2024-01-01T00:00:00Z'
  }
]

// 用户管理类
export class UserManager {
  private static users: User[] = [...predefinedUsers]

  /**image.png
   * 验证用户登录
   * @param username 用户名
   * @param password 密码
   * @returns 用户信息或null
   */
  static authenticate(username: string, password: string): User | null {
    const uname = (username || '').trim().toLowerCase()
    const pwd = (password || '').trim()
    const user = this.users.find(u =>
      u.isActive &&
      u.username.toLowerCase() === uname &&
      u.password === pwd
    )

    if (user) {
      // 更新最后登录时间
      user.lastLoginAt = new Date().toISOString()
    }

    return user || null
  }

  /**
   * 根据用户名获取用户
   * @param username 用户名
   * @returns 用户信息或null
   */
  static getUserByUsername(username: string): User | null {
    return this.users.find(u => u.username === username && u.isActive) || null
  }

  /**
   * 根据ID获取用户
   * @param id 用户ID
   * @returns 用户信息或null
   */
  static getUserById(id: string): User | null {
    return this.users.find(u => u.id === id && u.isActive) || null
  }

  /**
   * 获取所有用户（仅超级管理员可用）
   * @returns 用户列表
   */
  static getAllUsers(): User[] {
    return this.users.filter(u => u.isActive)
  }

  /**
   * 根据角色获取用户列表
   * @param role 用户角色
   * @returns 用户列表
   */
  static getUsersByRole(role: UserRole): User[] {
    return this.users.filter(u => u.role === role && u.isActive)
  }

  /**
   * 根据科室获取用户列表
   * @param department 科室名称
   * @returns 用户列表
   */
  static getUsersByDepartment(department: string): User[] {
    return this.users.filter(u => u.department === department && u.isActive)
  }

  /**
   * 创建新用户（仅超级管理员可用）
   * @param userData 用户数据
   * @returns 创建的用户
   */
  static createUser(userData: Omit<User, 'id' | 'createdAt' | 'isActive'>): User {
    const newUser: User = {
      ...userData,
      id: `u${Date.now()}`,
      createdAt: new Date().toISOString(),
      isActive: true
    }

    this.users.push(newUser)
    return newUser
  }

  /**
   * 更新用户信息
   * @param id 用户ID
   * @param updates 更新数据
   * @returns 更新后的用户或null
   */
  static updateUser(id: string, updates: Partial<User>): User | null {
    const userIndex = this.users.findIndex(u => u.id === id)
    if (userIndex === -1) return null

    this.users[userIndex] = { ...this.users[userIndex], ...updates }
    return this.users[userIndex]
  }

  /**
   * 禁用用户（软删除）
   * @param id 用户ID
   * @returns 是否成功
   */
  static deactivateUser(id: string): boolean {
    const user = this.users.find(u => u.id === id)
    if (!user) return false

    user.isActive = false
    return true
  }

  /**
   * 修改密码
   * @param username 用户名
   * @param oldPassword 旧密码
   * @param newPassword 新密码
   * @returns 是否成功
   */
  static changePassword(username: string, oldPassword: string, newPassword: string): boolean {
    const user = this.authenticate(username, oldPassword)
    if (!user) return false

    user.password = newPassword
    return true
  }

  /**
   * 获取用户统计信息
   * @returns 统计数据
   */
  static getUserStats() {
    const activeUsers = this.users.filter(u => u.isActive)

    return {
      total: activeUsers.length,
      byRole: {
        [UserRole.SUPER_ADMIN]: activeUsers.filter(u => u.role === UserRole.SUPER_ADMIN).length,
        [UserRole.DEAN]: activeUsers.filter(u => u.role === UserRole.DEAN).length,
        [UserRole.DIRECTOR]: activeUsers.filter(u => u.role === UserRole.DIRECTOR).length,
        [UserRole.DOCTOR]: activeUsers.filter(u => u.role === UserRole.DOCTOR).length,
        [UserRole.NURSE]: activeUsers.filter(u => u.role === UserRole.NURSE).length
      },
      departments: [...new Set(activeUsers.map(u => u.department).filter(Boolean))].length
    }
  }

  /**
   * 验证用户名是否可用
   * @param username 用户名
   * @returns 是否可用
   */
  static isUsernameAvailable(username: string): boolean {
    return !this.users.some(u => u.username === username)
  }
}

// 当前登录用户管理
export class AuthManager {
  private static readonly STORAGE_KEY = 'currentUser'

  /**
   * 登录用户
   * @param user 用户信息
   * @param token 认证token（可选）
   */
  static login(user: User, token?: string): void {
    // 兼容新老存储：优先使用新键位
    const safeUser = {
      id: user.id,
      username: user.username,
      role: user.role,
      email: user.email,
    }

    try {
      // 保存用户信息
      localStorage.setItem('user_info', JSON.stringify(safeUser))
      localStorage.setItem('isLoggedIn', 'true') // 兼容旧逻辑
      
      // 如果提供了token，保存token
      if (token) {
        localStorage.setItem('auth_token', token)
        console.log('[AuthManager] Token已保存:', token.substring(0, 20) + '...')
      }
      
      console.log('[AuthManager] 用户登录信息已保存:', safeUser)
    } catch (error) {
      console.error('[AuthManager] 保存登录信息失败:', error)
    }
    
    // 旧键位保底（避免遗留逻辑报错）
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify({
        ...safeUser,
        name: (user as any).name,
        department: (user as any).department,
        position: (user as any).position,
        avatar: (user as any).avatar,
        phone: (user as any).phone,
      }))
    } catch (error) {
      console.error('[AuthManager] 保存兼容用户信息失败:', error)
    }
  }

  /**
   * 登出用户
   */
  static logout(): void {
    try {
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_info')
      localStorage.removeItem(this.STORAGE_KEY)
      localStorage.removeItem('isLoggedIn')
      if (typeof window !== 'undefined') {
        try {
          const { default: useAuthStore } = require('@/stores/authStore')
          useAuthStore.getState().logout()
        } catch {}
      }
    } catch {}
  }

  /**
   * 获取当前登录用户
   * @returns 当前用户或null
   */
  static getCurrentUser(): Omit<User, 'password'> | null {
    try {
      const userInfo = localStorage.getItem('user_info')
      if (userInfo) return JSON.parse(userInfo)
      const userData = localStorage.getItem(this.STORAGE_KEY)
      return userData ? JSON.parse(userData) : null
    } catch {
      return null
    }
  }

  /**
   * 检查是否已登录
   * @returns 是否已登录
   */
  static isLoggedIn(): boolean {
    try {
      const token = localStorage.getItem('auth_token')
      const userInfo = localStorage.getItem('user_info')
      const isLoggedInFlag = localStorage.getItem('isLoggedIn')
      const currentUser = this.getCurrentUser()
      
      console.log('[AuthManager] 认证状态检查:', {
        hasToken: !!token,
        hasUserInfo: !!userInfo,
        isLoggedInFlag,
        hasCurrentUser: !!currentUser
      })
      
      // 优先使用新的认证逻辑：token + userInfo
      if (token && userInfo) {
        console.log('[AuthManager] 使用token+userInfo认证通过')
        return true
      }
      
      // 兼容旧逻辑：isLoggedIn标志 + 用户信息
      if (isLoggedInFlag === 'true' && currentUser !== null) {
        console.log('[AuthManager] 使用兼容逻辑认证通过')
        return true
      }
      
      console.log('[AuthManager] 认证失败，需要重新登录')
      return false
    } catch (error) {
      console.error('[AuthManager] 认证检查异常:', error)
      return false
    }
  }

  /**
   * 检查当前用户是否有指定权限
   * @param permission 权限
   * @returns 是否有权限
   */
  static hasPermission(permission: string): boolean {
    const user = this.getCurrentUser()
    if (!user) return false

    // 集成权限检查逻辑，包含自定义权限
    return PermissionChecker.hasPermission(user.role, permission as any, user.id)
  }

  /**
   * 检查当前用户是否可以访问指定页面
   * @param page 页面标识
   * @returns 是否可以访问
   */
  static canAccessPage(page: string): boolean {
    const user = this.getCurrentUser()
    if (!user) return false

    return PermissionChecker.canAccessPage(user.role, page, user.id)
  }
}